package com.stox.indicator;

import java.util.List;

import lombok.Data;

import org.springframework.stereotype.Component;

import com.stox.dto.Bar;
import com.stox.dto.BarValue;
import com.stox.indicator.RelativeStrengthIndex.Configuration;

@Component
public class RelativeStrengthIndex implements Occilator<Configuration> {

	@Data
	public static class Configuration{
		private int span = 30;
		private BarValue barValue = BarValue.CLOSE;
	}

	@Override
	public Configuration createDefaultConfiguration() {
		return new Configuration();
	}

	@Override
	public Double getValue(Configuration configuration, List<Bar> bars,
			int index) {
		throw new UnsupportedOperationException();
	}
	
	@Override
	public Double[] getValues(Configuration configuration, Double[] values){
		throw new UnsupportedOperationException();
	}

	public Double[] getValues(Configuration configuration, List<Bar> bars) {
		Double[] result = new Double[bars.size()];
		int span = configuration.getSpan();
		BarValue barValue = configuration.getBarValue();
		int size = bars.size();
		double averageGain = 0;
		double averageLoss = 0;
		double previousBarValue = 0;
		for(int i = size - 1; i >= 0; i--){
			double currentBarValue = barValue.get(bars.get(i));
			if(previousBarValue > currentBarValue){
				averageLoss = (averageLoss*(span - 1) + Math.abs(currentBarValue - previousBarValue))/span;
			}else{
				averageGain = (averageGain*(span - 1) + Math.abs(currentBarValue - previousBarValue))/span;
			}
			if(i <= size - 1 - span){
				result[i] = 100 - 100/((averageGain/averageLoss) + 1);
			}
			previousBarValue = currentBarValue;
		}
		return result;
	}

	@Override
	public Double getHigh() {
		return 100d;
	}

	@Override
	public Double getLow() {
		return 0d;
	}

	private Double[] levels = {30d,70d};
	
	@Override
	public Double[] getLevels() {
		return levels;
	}
	
}
